﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace QunYing.Common
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true, InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class WarnInfoSeveice : IWarnInfoService
    {
        public static WarnInfoSeveice Instance = new WarnInfoSeveice();

        public event Action<string, int> WarnInfoReceived;

        private System.Timers.Timer timer = new System.Timers.Timer();

        private Dictionary<string, OperationContext> contexts = new Dictionary<string, OperationContext>();

        private Dictionary<string, OperationContext> admin_contexts = new Dictionary<string, OperationContext>();

        public WarnInfoSeveice()
        {
            timer.AutoReset = false;
            timer.Interval = 1000 * 10;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }

        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer.Stop();
            lock (obj)
            {
                foreach(var v in this.admin_contexts.Keys)
                {
                    try
                    {
                        IWarnInfoHandle handle = this.admin_contexts[v].GetCallbackChannel<IWarnInfoHandle>();
                        handle.ProcessWarnInfo(-1);
                    }
                    catch (Exception ex)
                    {
                        this.admin_contexts.Remove(v);
                    }
                }
            }
            timer.Start();
        }

        private object obj = new object();

        #region IWarnInfoService 成员

        public void RegisterListener(string name,string otherInfo)
        {
            lock (obj)
            {
                Loger.Log.Info(string.Format(string.Format("用户注册警告信息事件成功：{0}",name)));
                if (otherInfo != "经销商")
                {
                    try
                    {
                        if (admin_contexts.Keys.Contains(name))
                        {
                           // admin_contexts[name].Channel.Close();
                            admin_contexts[name] = OperationContext.Current;
                        }
                        else
                        {
                            admin_contexts.Add(name, OperationContext.Current);
                        }
                    }
                    catch (Exception ex)
                    {
                        QunYing.Common.Loger.Log.Error("注册警告信息处理时发生了错误：" + ex.Message);
                    }
                }
                else
                {
                    try
                    {
                       if (contexts.Keys.Contains(name))
                        {
                            //contexts[name].Channel.Close();
                            contexts[name] = OperationContext.Current;
                        }
                        else
                        {
                            contexts.Add(name, OperationContext.Current);
                        }
                    }
                    catch (Exception ex)
                    {
                        QunYing.Common.Loger.Log.Error("注册警告信息处理时发生了错误：" + ex.Message);
                    }
                }
            }
        }

        public void UnregisterListener(string name, string otherInfo)
        {
            lock (obj)
            {
                try
                {
                    if (otherInfo != "经销商")
                    {
                        if (this.admin_contexts.Keys.Contains(name))
                        {
                            var v = this.contexts[name];
                            this.contexts.Remove(name);
                            v.Channel.Close();
                        }
                    }
                    else
                    {
                        if (this.contexts.Keys.Contains(name))
                        {
                            var v = this.contexts[name];
                            this.contexts.Remove(name);
                            v.Channel.Close();
                        }
                    }
                }
                catch(Exception ex)
                {
                }
            }
        }

        public void ProcessWarnInfo(string name, int warnInfoDataKey)
        {
            lock (obj)
            {
                try
                {
                    Loger.Log.Info("收到告警信息！");
                    if (this.WarnInfoReceived != null)
                        this.WarnInfoReceived(name, warnInfoDataKey);

                    if (this.contexts.Keys.Contains(name))
                    {
                        var temp = this.contexts[name];
                        IWarnInfoHandle handle = temp.GetCallbackChannel<IWarnInfoHandle>();
                        handle.ProcessWarnInfo(warnInfoDataKey);
                        Loger.Log.Info("回调成功告警信息！"+name);
                    }
                    else 
                    {
                        Loger.Log.Info("经销商不在线！");
                    }
                    foreach (var v in this.admin_contexts.ToArray())
                    {
                        try
                        {
                            var vvv = v.Value;
                            IWarnInfoHandle handle = vvv.GetCallbackChannel<IWarnInfoHandle>();
                            handle.ProcessWarnInfo(warnInfoDataKey);
                        }
                        catch
                        {
                            this.admin_contexts.Remove(v.Key);
                        }
                    }

                }
                catch (Exception ex)
                {
                    contexts.Remove(name);
                    QunYing.Common.Loger.Log.Error("处理告警信息回调客户端出现异常：" + ex.Message);
                }
            }
        }

        #endregion
    }
}
